package qing.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import qing.entity.Person;
import qing.entity.moneyLog;
//import qing.service.moneyLogService;
import qing.service.PersonService;
import qing.common.u.HttpSessionProvider;
import qing.common.u.usession;

@Controller
public class RegController {

	@Autowired
	private PersonService personService;



	
/*	
 * RequestParam 如果是get方式，则为url中的参数，如果为post等方式，则为form中的参数
 * @RequestMapping(value = "reg")   //访问网页 http://localhost:8080/SSPH/reg?name=whx 时到达这一步处理，此时页面未渲染
	public String reg(@RequestParam(value="name",required=false,defaultValue='cs') String username) {  // 接收url中的name参数，也可以没有，默认为字符串‘cs’
	}*/
	
	/**
	 * 使用 @RequestMapping 来映射请求URL， 映射的名称必须和RequestMapping的名称一致，区分大小写
	 * 访问localhost/ssm/reg,转到当前处理程序，然后发送给reg.jsp页面 通过视图解析器解析，转发结果为：前缀+名称+后缀
	 */
	/*@RequestMapping(value = "reg", method = RequestMethod.GET)
	public String reg(Map<String, Object> map) {
		System.out.println("reg page,path:" + System.getProperty("user.dir"));
		map.put("person", new Person());
		moneyLog log = imoneyLog.find(moneyLog.class, 1);
		System.out.println(log.getTitle());
		System.out.println("开始睡眠1S……");
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("person:" + log.getPerson());
		return "reg";
	}

	@RequestMapping(value = "test", method = RequestMethod.GET)
	public String test(Map<String, Object> map) {
		System.out.println("test page,path:" + System.getProperty("user.dir"));
		map.put("test", "122335511");
		return "reg";		
	}*/

	// freemarker 解析模板 http://localhost:8080/SSPH/test.html?name=whx
	@RequestMapping(value = "test.html", method = RequestMethod.GET)
	public String index(String name, Model model) {
		model.addAttribute("name", name);
		model.addAttribute("message", "welcome to FreeMarker!");
		return "hello";
	}

	// http://localhost:8080/SSPH/testFreemarker?a=123
	@RequestMapping(value = "/testFreemarker", method = RequestMethod.GET)
	public ModelAndView testFreemarker(@RequestParam(value = "a", required = false) String a) throws Exception {
		ModelAndView mv = new ModelAndView();
		// User user = new User("may", 21);
		Person person = new Person("test", "123456", 100f);
		List<String> list = new ArrayList<String>();
		list.add("Jack1");
		list.add("Jack2");
		list.add("Jack3");
		mv.addObject("list", list);
		mv.addObject("user", person);
		mv.addObject("name", "王红喜");
		mv.addObject("param", new String(a.getBytes("iso8859-1"), "utf-8"));
		mv.setViewName("test");
		return mv;
	}

	/*
	 * @RequestMapping(value="reg",method=RequestMethod.POST) public String
	 * reg(@RequestParam(value="password2") String pwd ) {
	 * System.out.println("pwd:"+pwd); return "success"; }
	 */

	// 提交注册
	@RequestMapping(value = "reg", method = RequestMethod.POST)
	public String eidtuserpost(@Valid Person u, BindingResult result, @RequestParam(value = "password2") String pwd) {
		if (result.getErrorCount() > 0) {
			// 打印出错误信息，调试用
			for (FieldError error : result.getFieldErrors()) {
				System.out.println(error.getField() + ":" + error.getDefaultMessage());
			}
			System.out.println("发现了错误：");
			return "reg";
		}
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		u.setIpCreated(request.getRemoteAddr());
		u.setIpLastActived(request.getRemoteAddr());
		u.setDateCreated(new Date());
		u.setDateLastActived(new Date());
		System.out.println("开始保存1");
		personService.save(u);
		System.out.println("开始转向4");
		return "redirect:/login";

	}

	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String login(HttpServletRequest request, HttpSession session) {
		
		  Person person = personService.getPersonByAccount("whx");
		  session.setAttribute("user", person);
		  System.out.println("准备登录");
		  return "redirect:/admin/index";
		
/*
		Object object = request.getSession().getAttribute("user");
		System.out.println(object);
		if (object != null) {
			return "redirect:/admin/index";
		}
		return "login";
		
		*/
	}

	@RequestMapping(value = "index", method = RequestMethod.GET)
	public String index() {
System.out.println("old index");
		return "admin/cms/index";
	}

	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String login(HttpServletRequest request,Person p, @RequestParam(value = "valcode") String valcode,Map<String,Object> map) {
		String login="login";
		usession usession=new HttpSessionProvider();
		if (p.getUsername().isEmpty() || p.getPassword().isEmpty() || valcode.isEmpty()) {
			map.put("msg", "请填写用户名和密码"); 
			return login;
		}
		String scode = (String)usession.getAttribute(request, "verCode");
		if (!scode.equals(valcode.toLowerCase())) {			
			map.put("msg", "验证码错误，应为" +scode); 
			return login;
		}
		Person person = personService.getPerson(p.getUsername(), p.getPassword());
		if (person == null) {
			map.put("msg", "用户名或密码错误"); 
			return login;
		}
		person.setDateLastActived(new Date());
		person.setIpLastActived(request.getRemoteAddr());
		usession.setAttribute(request, null, "user", person);
		personService.update(person);
		return "redirect:/admin/index";
	}

	@RequestMapping("logon")
	public String logon(HttpSession session) {
		session.setAttribute("user", null);
		return "/login";
	}

}
